package com.yantu.controller.leader;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yantu.bean.Class;
import com.yantu.bean.ClassStudent;
import com.yantu.bean.User;
import com.yantu.bean.UserEventLog;
import com.yantu.mapper.ClassMapper;
import com.yantu.mapper.ClassStudentMapper;
import com.yantu.mapper.UserEventLogMapper;
import com.yantu.mapper.UserMapper;
import com.yantu.util.RedisUtils;
import com.yantu.util.Result;
import com.yantu.view.leader.LeaderClassView;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 综合实训课程设计
 * @since 2022-08-11
 */
@RestController
@RequestMapping("/leader")
@ApiModel("队长端班级接口")
public class LeaderClassController extends leaderUserLogController{

    @Autowired
    ClassMapper classMapper;

    @Autowired
    ClassStudentMapper classStudentMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    RedisUtils redisUtils;


    @GetMapping("/myPage/{id}")
    @ApiOperation("队长个人主页")
    public Result myPage(@PathVariable("id") Integer id){
        if(redisUtils.haskeysf("leaderMyPage"+id)){
            List<Class> classList = (List<Class>) redisUtils.getValue("leaderMyPage"+id);
            return Result.succ(200, "成功",classList );
        }else {
            QueryWrapper<Class> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", id);
            List<Class> classList = classMapper.selectList(queryWrapper);
            redisUtils.saveValue("leaderMyPage"+id,classList);
            return Result.succ(200, "查询成功", classList);
        }
    }

    @PostMapping("/class")
    @ApiOperation("创建班级")
    public Result addClass(@RequestBody Class classL){

        Class addClass=new Class();
        addClass.setName(classL.getName());
        addClass.setUserId(classL.getUserId());
        addClass.setCreateTime(new Date());
        int result = classMapper.insert(classL);
        if(result>0){
            User user = userMapper.selectById(classL.getUserId());
            String msg = "用户"+user.getUserName()+"成功创建班级"+classL.getName();
            super.leaderAddLog(user,msg);
            redisUtils.delAll();
            return Result.succ(200,"创建成功",null);
        }else {
            return Result.fail("创建失败");
        }
    }

    @DeleteMapping("/class/{id}")
    @ApiOperation("根据班级id删除班级")
    public Result DeleteClassById(HttpServletRequest request,@PathVariable("id") Integer id){
        String token = request.getHeader("token");
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("token",token);
        User user = userMapper.selectOne(queryWrapper);
        int result =classMapper.deleteById(id);
        if(result>0){
            String msg = "小组长成功删除班级"+id;
            super.leaderAddLog(user,msg);
            return Result.succ(200,"删除成功",null);
        }else{
            String msg = "小组长失败删除班级"+id;
            super.leaderAddLog(user,msg);
            return Result.fail("删除失败");
        }
    }

    //获取小组学生
    @GetMapping("/classStu/{id}")
    @ApiOperation("获取小组学生")
    public Result deleteStuInClass(@PathVariable("id") Integer id){
        if(redisUtils.haskeysf("leaderClassStu"+id)){
            List<User> userList = (List<User>) redisUtils.getValue("leaderClassStu"+id);
            return Result.succ(200, "成功",userList );
        }else {
            QueryWrapper<ClassStudent> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("class_id", id);
            List<ClassStudent> ClassStudentList = classStudentMapper.selectList(queryWrapper);
            if (ClassStudentList != null) {
                List<User> userList = new ArrayList<>();
                for (ClassStudent classStudent : ClassStudentList) {
                    userList.add(userMapper.selectById(classStudent.getUserId()));
                }
                if (userList != null) {
                    redisUtils.saveValue("leaderClassStu"+id,userList);
                    return Result.succ(200, "查询成功", userList);
                } else {
                    return Result.fail("查询失败");
                }
            }
            return Result.fail("查询失败");
        }
    }

    //删除小组学生
    @DeleteMapping("/classStu")
    @ApiOperation("移除小组学生")
    public Result deleteStuInClass(@ModelAttribute LeaderClassView leaderClassView){
        QueryWrapper<ClassStudent> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("class_id",leaderClassView.getId());
        queryWrapper.eq("user_id",leaderClassView.getUserId());
        ClassStudent classStudent=classStudentMapper.selectOne(queryWrapper);
        User user = userMapper.selectById(leaderClassView.getUserId());
        int result= classStudentMapper.deleteById(classStudent.getId());
        if(result>0){
            String msg = "小组长成功删除学生"+leaderClassView.getUserId();
            super.leaderAddLog(user,msg);
            redisUtils.delAll();
            return Result.succ("删除成功",null);
        }else{
            String msg = "小组长失败删除学生"+leaderClassView.getUserId();
            super.leaderAddLog(user,msg);
            return Result.fail("删除失败");
        }
    }

    //小组编辑
    @PutMapping("/class")
    @ApiOperation("编辑班级名字")
    public Result editSubjectInfo(@ModelAttribute Class classL){
        UpdateWrapper updateWrapper=new UpdateWrapper<>();
        updateWrapper.eq("id",classL.getId());
        if(classL.getName()!=null){
            updateWrapper.set("name",classL.getName());}
        int result=classMapper.update(null, updateWrapper);
        if(result>0){
            //管理员登录的日志
            UserEventLog userLog = new UserEventLog();
            userLog.setCreateTime(new Date());
            userLog.setUserName("admin");
            userLog.setRealName("管理员");
            userLog.setUserId(2);
            userLog.setContent("小组长成功编辑班级"+classL.getName()+"信息");
            int result2 = userEventLogMapper.insert(userLog);
            redisUtils.delAll();
            return Result.succ(200,"编辑成功",null);
        }else{
            //管理员登录的日志
            UserEventLog userLog = new UserEventLog();
            userLog.setCreateTime(new Date());
            userLog.setUserName("admin");
            userLog.setRealName("管理员");
            userLog.setUserId(2);
            userLog.setContent("小组长失败编辑班级"+classL.getName()+"信息");
            int result2 = userEventLogMapper.insert(userLog);
            return Result.fail("编辑失败");
        }
    }

    @GetMapping("/classList")
    @ApiOperation("班级模糊查询（班级名）")
    public Result selectClassList(@ModelAttribute LeaderClassView classView){
        PageHelper.startPage(classView.getPageIndex(), classView.getPageSize());
        if(redisUtils.haskeysf("leaderClassList"+classView)){
            PageInfo pageInfo = (PageInfo) redisUtils.getValue("leaderClassList"+classView);
            return Result.succ(200, "成功",pageInfo );
        }else {
            QueryWrapper<Class> queryWrapper = new QueryWrapper<>();
            if (classView.getName() != null) {
                queryWrapper.like("name", classView.getName());
            }
            queryWrapper.eq("user_id", classView.getUserId());

            List<Class> classList = classMapper.selectList(queryWrapper);
            PageInfo pageInfo = new PageInfo(classList);
            redisUtils.saveValue("leaderClassList"+classView,pageInfo);
            return Result.succ(200, "查询成功", pageInfo);
        }
    }

    @GetMapping("/classPage")
    @ApiOperation("班级分页")
    public Result ClassList(@ModelAttribute LeaderClassView classView) {
        if (redisUtils.haskeysf("leaderClassPage" + classView)) {
            List<Class> classList = (List<Class>) redisUtils.getValue("leaderClassPage" + classView);
            return Result.succ(200, "成功", classList);
        } else {
            PageHelper.startPage(classView.getPageIndex(), classView.getPageSize());
            QueryWrapper<Class> queryWrapper = new QueryWrapper<>();
            if (classView.getUserId() != null) {
                queryWrapper.eq("user_id", classView.getUserId());
                //查询班级列表
                List<Class> classList = classMapper.selectList(queryWrapper);
                //统计该队长的班级数量
                int count = classMapper.selectCount(queryWrapper);
                PageInfo pageInfo = new PageInfo(classList);
                Map map = new HashMap<>();
                map.put("count", count);
                map.put("classList", pageInfo);
                redisUtils.saveValue("leaderClassPage"+classView,map);
                return Result.succ(200, "查询成功", map);
            } else {
                return Result.fail("查询失败");
            }
        }
    }
}

